package com.ruoyi.project.system.controller;

import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.Appointment;
import com.ruoyi.project.system.mapper.AppointmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/appointment")
public class AppointmentController {

    @Autowired
    private AppointmentMapper appointmentMapper;

    /**
     * 保存预约记录（新增预约号唯一性校验）
     */
    @PostMapping("/save")
    @Transactional // 事务保障：避免并发插入重复数据
    public AjaxResult saveAppointment(@RequestBody Appointment appointment) {
        // 第一步：校验预约号是否已存在（主动校验）
        int count = appointmentMapper.countByResId(appointment.getResId());
        if (count > 0) {
            // 返回明确的重复提示，供前端重试
            return AjaxResult.error("预约号已存在");
        }

        // 第二步：插入数据（数据库主键约束兜底）
        try {
            int rows = appointmentMapper.save(appointment);
            return rows > 0 ? AjaxResult.success("预约成功") : AjaxResult.error("预约失败");
        } catch (Exception e) {
            // 捕获数据库主键冲突异常（极端并发场景）
            if (e.getMessage().contains("Duplicate entry") && e.getMessage().contains("res_id")) {
                return AjaxResult.error("预约号已存在");
            }
            return AjaxResult.error("预约失败：" + e.getMessage());
        }
    }
}